import axios from 'axios';

// 创建API实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080',
  timeout: 30000
});

// 发送消息（含请求成功/失败判断）
export const sendMessage1 = async (message1, urlSuffix, onChunk, userid) => {
  return new Promise((reject, resolve) => {
    const userids = userid;
    const params = new URLSearchParams({
      message: JSON.stringify([{ role: 'user', content: message1 }]),
      stream: 'true',
      userid: userids
    });
    const url = `${api.defaults.baseURL}${urlSuffix}?${params}`;
    const eventSource = new EventSource(url);
    let isConnected = false; 

    //连接成功
    eventSource.onopen = () => {
      isConnected = true; 
    };

    //接收服务器发送的消息
    eventSource.onmessage = (event) => {
      if (event.data === '[DONE]') {
        eventSource.close();
        resolve(true); // 成功：完整接收数据
        return;
      }
      onChunk(event.data); 
    };

    // 3. 错误处理（连接失败）
    eventSource.onerror = (error) => {
      if (!isConnected) {
        console.error("EventSource 请求失败：无法建立连接");
        onChunk("请求失败：无法连接到服务器"); // 通知前端
        eventSource.close();
        reject(new Error('请求失败：无法建立连接'));
      } else {
        console.error("EventSource 连接中断");
        eventSource.close();
        reject(new Error('连接已中断'));
      }
    };
  });
};